package com.mediacloud.app.newsmodule.fragment.video.vod

import android.annotation.SuppressLint
import android.net.ConnectivityManager
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.NetworkUtils
import com.chinamcloud.project.shanshipin.activity.TikTokActivity
import com.eventTrack.CDPTrackReportManager
import com.eventTrack.TXReportManager
import com.mediacloud.app.assembly.util.isFastClick
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.ArticleListData
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.model.view.floatwin.FloatButtonGroup
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.activity.microlive.BaseRecyclerAdapter
import com.mediacloud.app.newsmodule.adaptor.component.IExposure
import com.mediacloud.app.newsmodule.adaptor.video.vod.SmallVideoListAdapter
import com.mediacloud.app.newsmodule.fragment.ListPreLoadKit
import com.mediacloud.app.newsmodule.fragment.nav2.BaseRecyclerListFragment
import com.mediacloud.app.newsmodule.utils.BindEventBus
import com.mediacloud.app.newsmodule.utils.CacheData
import com.mediacloud.app.newsmodule.utils.FacadeInvoker
import com.mediacloud.app.newsmodule.utils.SpaceItemDecoration
import com.mediacloud.app.reslib.enums.XKey
import com.mediacloud.app.reslib.util.DataInvokeUtil
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.tencent.mmkv.MMKV
import com.utils.ExposurePoolService
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers

/**
Date:2020/4/21
Author:Wy
 */
class SmallVideoNewsListFragment : BaseRecyclerListFragment<SmallVideoListAdapter>(),
    BaseRecyclerAdapter.ItemClickListener {
    private var pageSize = 20
    var preLoadKit: ListPreLoadKit<ArticleListData>? = null

    var count = 2


    override fun getRecyclerAdapter(): SmallVideoListAdapter? {
        val movieGridAdapter = SmallVideoListAdapter(activity)
        movieGridAdapter.isThree = (count == 3)
        movieGridAdapter.setItemClickListener(this)
        return movieGridAdapter
    }

    override fun getLayoutManager(): RecyclerView.LayoutManager? {
        count = if (catalogItem.catalogStyle == 4) {
            2
        } else {
            3
        }
        val layoutManager = GridLayoutManager(activity, count)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        return layoutManager
    }
    override fun initView() {
        super.initView()
        BindEventBus(this, recyclerAdapter)
        preLoadKit = object : ListPreLoadKit<ArticleListData>(requireContext(), refreshLayout) {
            override fun onSetData(data: ArticleListData) {
                setData(data)
            }

            override fun onPreload(preNum: Int) {
                preload(preNum)
            }
        }
        recyclerView.addItemDecoration(
            SpaceItemDecoration(
                context?.resources?.getDimensionPixelSize(
                    R.dimen.dimen2
                )!!
            )
        )
        val manager = recyclerView.layoutManager as GridLayoutManager
        refreshLayout.setEnableLoadMore(false)
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val lastVisibleItem = manager.findLastVisibleItemPosition()
                if (lastVisibleItem == manager.itemCount - 1) {
                    preLoadKit?.onLoadMore()
                }
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    app_jhapp_video_imp()
                }
            }
        })
        showStateView(TYPE_LOADING, false)
        recyclerView.setHasFixedSize(true)
        recyclerView.itemAnimator = null
        retryTips?.setOnClickListener {
            if (NetworkUtils.isConnected()) {
                showStateView(TYPE_LOADING, false)
                onRefresh(refreshLayout)
            }
        }
        getDate()
    }

    fun auto2Detail(index: Int) {
        if (!checkNetType()){
            return
        }
        val isAutoPlay = MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false)
        if (!isAutoPlay && mNetType != ConnectivityManager.TYPE_WIFI) {
            return
        }
        recyclerAdapter?.let {
            if (it.data.isNotEmpty()) {
                val item = it.getItem(0)
                val arrayList = it.data as ArrayList<ArticleItem>
                CDPTrackReportManager.getInstance().ShortVideoClick(item,0)
                //小视频类型传5
                if (item.type == TypeX.NEWS.MICRO_VIDEO)//短视频文稿
                {
                    FacadeInvoker.getFacadeData(requireContext(), item.id.toString())
                    TikTokActivity.startActivity(
                        requireContext(),
                        arrayList,
                        index,
                        catalogItem.catid,
                        pageIndex,
                        0,
                        true,
                        true
                    )
                } else {
                    FacadeInvoker.getFacadeData(requireContext(), item.id.toString(), 1)
                    TikTokActivity.startActivity(
                        requireContext(),
                        arrayList,
                        index,
                        catalogItem.catid,
                        pageIndex,
                        0
                    )
                }
            }
        }
    }

    var isFirst = true

    override fun onItemClick(index: Int, isFromAdaptor: Boolean, adapter: BaseRecyclerAdapter<*>?) {
        if (isFastClick()) {
            val item = recyclerAdapter.getItem(index)
            val arrayList = recyclerAdapter.data as ArrayList<ArticleItem>
            CDPTrackReportManager.getInstance().ShortVideoClick(item,index)
            //小视频类型传5
            if (item.type == TypeX.NEWS.MICRO_VIDEO)//短视频文稿
            {
                FacadeInvoker.getFacadeData(requireContext(), item.id.toString())
                TikTokActivity.startActivity(
                    requireContext(),
                    arrayList,
                    index,
                    catalogItem.catid,
                    pageIndex,
                    0,
                    true
                )
                if ("视频" == TXReportManager.getInstance().firstTabInfo.tabName) {
                    TXReportManager.getInstance()
                        .app_jhapp_video_interact("点击查看", catalogItem?.name, item,index)
                }
            } else {
                FacadeInvoker.getFacadeData(requireContext(), item.id.toString(), 5)
                TikTokActivity.startActivity(
                    requireContext(),
                    arrayList,
                    index,
                    catalogItem.catid,
                    pageIndex,
                    0
                )
            }

        }
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        Log.w(ListPreLoadKit.LTAG, "触发了 RefreshLayout onLoadMore")
        preLoadKit?.getMoreDate()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        preLoadKit?.onRefresh()
        getDate()
    }

    @SuppressLint("CheckResult")
    private fun preload(preNum: Int) {
        DataInvokeUtil.getContentList(catalogID, preNum, pageSize, null).map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            temp
        }.subscribeOn(Schedulers.io()).onErrorReturn { null }
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ArticleListData> {
                override fun onSubscribe(d: Disposable) {
                }

                override fun onNext(t: ArticleListData) {
                    preLoadKit?.hasMore = t.more
                    //去初重复的数据 因为缓存的原因，在分页的时候可能会引起数据重复
                    val iterator = t.articleList.iterator()
                    val existData = recyclerAdapter.data
                    val existSize = existData.size
                    while (iterator.hasNext()) {
                        val d = iterator.next()
                        loop@ for (i in 0 until existSize) {
                            if (d.id == existData[i].id) {
                                iterator.remove()
                                break@loop
                            }
                        }
                    }
                    preLoadKit?.onPreloadSuccess(t, preNum)
                }

                override fun onError(e: Throwable) {
                    preLoadKit?.onPreloadFail(preNum)
                }

                override fun onComplete() {

                }
            })
    }

    private fun getDate() {
        DataInvokeUtil.getContentList(catalogID, preLoadKit!!.pageNum, pageSize, null).map {
            val temp = ArticleListData()
            temp.readFromJson(it.body())
            preLoadKit?.hasMore = temp.more
            temp
        }.onErrorReturn { null }
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : Observer<ArticleListData> {
                override fun onSubscribe(d: Disposable) {}

                @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
                override fun onNext(t: ArticleListData) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }

                    if (preLoadKit!!.pageNum == 1 && t.articleList.isNotEmpty()) {
                        CacheData.saveData(requireContext(), catalogID, t.orginData.toString())
                    }
                    refreshLayout.finishRefresh()
                    refreshLayout.finishLoadMore()
                    preLoadKit?.preLoadData?.add(t)
                    setData(t)
                    dataReady = true
                    if (hadChoosed) {
                        app_jhapp_video_imp()
                    }
                    preLoadKit?.preload()
                }

                override fun onError(e: Throwable) {
                    if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed) {
                        return
                    }
                    refreshLayout.finishRefresh(false)
                    refreshLayout.finishLoadMore()

                    val t =
                        CacheData.readData(requireContext(), catalogID, ArticleListData::class.java)

                    if (t != null && t.articleList.isNotEmpty()) {
                        closeStateView()
                        setData(t)
                    } else {
                        if (recyclerAdapter?.data?.size == 0) {
                            showStateView(TYPE_NET_NOT_GIVE_FORCE, false)
                        } else {
                            closeStateView()
                        }
                    }

                }

                override fun onComplete() {

                }
            })

    }


    private fun setData(t: ArticleListData) {
        if (activity == null || requireActivity().isFinishing || requireActivity().isDestroyed)
            return
        // ListPreLoadTool.preLoad2(requireContext(), t.articleList)
        if (preLoadKit!!.pageNum == 1) {
            val floatData = t.orginData.optJSONObject("data")
            if (FloatButtonGroup.haveFloatField(floatData)) {
                initFloatWin(floatData)
            } else {
                hideFloatWin()
            }
            recyclerAdapter.data.clear()
        }
        val size: Int = recyclerAdapter.itemCount
        recyclerAdapter.data.addAll(t.articleList)
        if (preLoadKit!!.pageNum == 1) {
            recyclerView.notifyDataSetChanged()
        } else {
            recyclerView.notifyItemRangeInserted(size, t.articleList.size)
        }
        if (recyclerAdapter?.data?.size == 0) {
            showStateView(TYPE_NO_CONTENT, false)
        } else {
            closeStateView()
        }

        if (preLoadKit!!.pageNum == 1 && isFirst && hadChoosed) {
            isFirst = false
            auto2Detail(0)
        }
    }


    override fun onResume() {
        super.onResume()
        if (recyclerAdapter.data.size != 0) {
            recyclerView.notifyDataSetChanged()
        }
    }


    override fun choosed() {
        super.choosed()
        auto2Detail(0)
        if (isAdded) {
            app_jhapp_video_imp()
        }
    }

    private var dataReady = false
    private val app_jhapp_video_impRunable: Runnable = Runnable {
        ExposurePoolService.getExecutorService().execute {
            try {
                val childCount = recyclerView.childCount
                TXReportManager.getExposureArticles(recyclerView, recyclerAdapter.data)
                    ?.forEachIndexed { position,obj->
                        if (TXReportManager.getInstance().firstTabInfo.tabName == "视听") {
                            CDPTrackReportManager.getInstance()
                                .ShortVideoExpose(obj, position, "精选视频")
                        }else{
                            CDPTrackReportManager.getInstance()
                                .ShortVideoExpose(obj, position)
                        }
                    }
//                for (i in 0 until childCount){
//                        TXReportManager.getExposureArticles(recyclerView, recyclerAdapter.data)
//                            ?.forEach { obj ->
//                                CDPTrackReportManager.getInstance().ShortVideoExpose(obj,i)
//                                TXReportManager.getInstance().app_jhapp_video_imp(
//                                    catalogItem?.name,
//                                    obj,
//                                    i
//                                )
//                            }
//                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun app_jhapp_video_imp() {
        if (!dataReady) return
        recyclerView?.apply {
            removeCallbacks(app_jhapp_video_impRunable)
            postDelayed(app_jhapp_video_impRunable, TXReportManager.EXPOSURE_DELAY)
        }
    }


    var mNetType = 0
    private fun checkNetType(): Boolean {
        if (context == null) return false
        val connectivityManager = getSystemService(requireContext(),ConnectivityManager::class.java)
        val networkInfo = connectivityManager?.activeNetworkInfo
        if (networkInfo != null && networkInfo.isAvailable) {
            mNetType = networkInfo.type
            return true
        }
        return false
    }

}